<template>
  <div class="login" id="earth_bg">
    <div class="login-box" v-show="showLoginWin">
      <div
        class="item"
        style="
          color: white;
          font-size: 30px;
          text-align: center;
          height: 80px !important;
          line-height: 80px;
        "
      >
        {{ systemName }}
      </div>
      <div class="item">
        <el-input
          v-model="form.username"
          type="text"
          placeholder="请输入账号"
          prefix-icon="el-icon-user"
        >
          <!-- <i slot="prefix" :class="icon" @click="showPass"></i> -->
        </el-input>
      </div>
      <div class="item">
        <el-input
          placeholder="请输入密码"
          v-model="form.password"
          prefix-icon="el-icon-lock"
          show-password
          @click.enter="clickLogin"
        >
          <!-- prefix suffix -->
          <!-- <i slot="prefix" style="font-style: normal; margin-right: 10px">用户名</i>
        <i slot="suffix" style="font-style: normal; margin-right: 10px">用户名</i> -->
        </el-input>
      </div>
      <!-- <div class="item captcha-box">
        <input
          @keyup.enter="clickLogin"
          type="text"
          placeholder="请输入验证码"
          v-model="form.captcha"
        />
        <span class="captcha">
          <img src="../../assets/logo.png" alt="验证码" />
        </span>
      </div> -->
      <div class="login-btn" @click="clickLogin">登 录</div>
    </div>

    <div class='systemEntryBtn' v-show="entryWinBtn">进入系统</div>
  </div>
</template>
<script>
import cookies from "@/utils/cookies";
import { login } from "@/api/user.js";

let scene,
  camera,
  renderer,
  controls,
  group,
  count = 0;
let earth;
let planeUp = [];
export default {
  props: {},
  data() {
    return {
      form: {
        username: "admin",
        password: "123456",
        captcha: "",
      },
      systemName: "临湘市乡村地名大数据系统",
      sprite: null,
      showLoginWin: false,
      entryWinBtn: true
    };
  },
  mounted() {
    this.initBg();
  },
  methods: {
    initBg() {
      this.init();
      this.animate();
      // this.run();

      //回车登录
      document.addEventListener("keyup", (event) => {
        if (event.keyCode == 13) {
          //keyCode=13是回车键
          this.clickLogin();
        }
      });

      const btn = document.getElementsByClassName('systemEntryBtn')[0];
      btn.addEventListener('click', () => {
        this.entryWinBtn = false;
        this.showLoginWin = true;
      });
    },

    init() {
      // 场景
      scene = new THREE.Scene();
      // let bgTexture = new THREE.TextureLoader().load("./threejs/images/bg.jpg");
      // scene.background = bgTexture;
      // 相机
      // camera = new THREE.PerspectiveCamera(75,window.innerWidth / window.innerHeight,0.1,1000);
      const s = 150;
      var width = window.innerWidth; //窗口宽度
      var height = window.innerHeight; //窗口高度
      var k = width / height; //窗口宽高比
      camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000); // 正交
      camera.position.z = 300;
      group = new THREE.Group();
      scene.add(group);

      // 渲染器
      renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
      renderer.setClearColor(0x000000, 0);
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.getElementById("earth_bg").appendChild(renderer.domElement);

      //控制器(旋转缩放)
      // controls = new OrbitControls( camera, renderer.domElement );
      // controls.minDistrance = 20;
      // controls.maxDistrance = 50;
      // controls.maxPolarAngle = Math.PI/2;
      // controls.addEventListener( 'change', render );

      //添加光源 (半球光 HemisphereLight)
      this.initLight();

      // 创建地球
      this.initEarth();

      // const vertexshader = `attribute float scale;

      // void main() {

      //   vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );

      //   gl_PointSize = scale * ( 300.0 / - mvPosition.z );

      //   gl_Position = projectionMatrix * mvPosition;//第一行和本行代码的目的是坐标系转换。<投影矩阵>*<视图矩阵>*<模型矩阵>*<顶点坐标> 相乘的顺序不能改变

      // }`;
      // const fragmentshader = `
      //   uniform vec3 color;

      //   void main() {

      //     if ( length( gl_PointCoord - vec2( 0.5, 0.5 ) ) > 0.475 ) discard;//不满足条件舍弃片元

      //     gl_FragColor = vec4( color, 1.0 );

      //   }`

      // let spriteGeometry=new THREE.BufferGeometry();
      //   let position=new Float32Array(50*50*3);//创建顶点存储空间
      //   let scales = new Float32Array( 50*50 );//创建存储尺寸的空间
      //   let i=0,j=0;
      //   for(let x=0;x<50;x++)
      //   {
      //       for(let y=0;y<50;y++)
      //       {
      //          position[i]=x*100-((50*100)/2);
      //          position[i+1]=0;//
      //          position[i+2]=y*100-((50*100)/2);
      //          scales[ j ] = 1;
      //          i+=3;
      //          j ++;
      //       }
      //   }
      //   spriteGeometry.addAttribute('position',new THREE.BufferAttribute(position,3));//把数据传入顶点着色器
      //   spriteGeometry.addAttribute('scale',new THREE.BufferAttribute(scales,1));//

      //   let spriteMaterial=new THREE.ShaderMaterial({//自定义着色器
      //       uniforms:{color: { value: new THREE.Color( 0x00CED1 ) },},
      //       vertexShader:vertexshader,//顶点着色器属性vertexShader的属性值是顶点着色器代码字符串
      //       fragmentShader:fragmentshader,//片元着色器属性fragmentShader的属性值是片元着色器代码字符串。

      //   });

      //   this.sprite=new THREE.Points(spriteGeometry,spriteMaterial);
      //   scene.add(this.sprite);

      // 绑定事件
      window.addEventListener("resize", this.onWindowResize);

    

      // var w = 16, h = 200;
      // const texture_up = this.createTexture(w, h, '101010', 4); // 展示的字体
      // texture_up.wrapS = THREE.RepeatWrapping; // 纹理设置
      // texture_up.wrapT = THREE.RepeatWrapping;
      // for (let index = 0; index <20; index++) {
      //   // texture_up.offset.y -= dt / 4;
      //   var mesh = null;
      //   if(Math.random() > 0.5){
      //     mesh = this.addUpPlaneMesh(w, h, texture_up, new THREE.Vector3(200 * Math.random() - 300,200 * Math.random() + 50,200 * Math.random()));
      //     scene.add(mesh);
      //     planeUp.push(mesh);
      //   }else {
      //     mesh = this.addUpPlaneMesh(w, h, texture_up, new THREE.Vector3(200 * Math.random() + 100,200 * Math.random() + 50,200 * Math.random()));
      //     scene.add(mesh);
      //     planeUp.push(mesh);
      //   }
      // }
    },
    animate() {
      requestAnimationFrame(this.animate);
      group.rotation.y -= 0.0005;
      // controls.update();
      this.render();
    },

    addUpPlaneMesh(width, height, textur, position) {
      var flyShader = {
        vertexshader: `
          varying vec2 vUv;
          varying float u_opacity;
          uniform sampler2D mytexture;
          uniform float time;
          uniform float vsize;
          uniform float vheight;
          void main() { 
            vUv = vec2(uv.x,uv.y - time);
            float op = (position.y + vheight / 2.0) / vheight;
            u_opacity = sin( op * 3.1415);
            vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
            gl_Position = projectionMatrix * mvPosition;
            gl_PointSize = vsize * 300.0 / (-mvPosition.z);
          }
        `,
        fragmentshader: `
          varying vec2 vUv;
          varying float u_opacity;
          uniform sampler2D mytexture;
          uniform vec3 vcolor; 
          void main() {
            gl_FragColor = vec4(vcolor,u_opacity) * texture2D(mytexture, vUv);
          }
        `
      }

      textur.repeat.x = 1;
      textur.repeat.y = 1;
      var planeGeometry = new THREE.PlaneGeometry(width, height, 1, 32); // PlaneBufferGeometry
      var material = new THREE.ShaderMaterial({
      uniforms: {
        time: { value: 0 },// time
        mytexture: { value: textur }, // 图片
        vsize: { value: 400 }, // 大小
        vcolor: { value: new THREE.Color(0.0, 1.0, 1.0) }, // 颜色
        vheight: { value: height }
      },
      transparent: true,
      depthTest: false,
      fragmentShader: flyShader.fragmentshader,
      vertexShader: flyShader.vertexshader
      })
      var plane_up = new THREE.Mesh(planeGeometry, material);
      // 旋转角度
      plane_up.rotation.x -= 0; /// Math.PI / 2;
      plane_up.position.copy(position);
      return plane_up;
    },
    
    createTexture(w, h, text, dpi) {
      //数字展示动效 
      dpi = dpi || 4;
      text = String(text);
      var width = w * dpi;
      var height = h * dpi;
      let canvas = document.createElement('canvas');
      canvas.width = width;
      canvas.height = height;
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "rgba(0,0,0,0)";
      var size = width / 2;
      ctx.font = size + "px 微软雅黑"//和css中的font一样，不过没有了行高
      ctx.textAlign = 'left'//和css中的text-align一样
      ctx.textBaseline = 'left'//这个是文本基线的意思
      ctx.fillStyle = '#ffffff';//你的字体颜色  
      for (let i = 0; i < text.length; i++) {
        ctx.fillText(text[i], (width - size) / 2, i * (height / (text.length - 1)));
      }
      var texture = new THREE.Texture(canvas);
      texture.needsUpdate = true;
      return texture;
    },


    render() {
      camera.lookAt(scene.position);
      renderer.render(scene, camera);
      // planeUp.forEach(function (mesh) {
      //   if (mesh.material) {
      //     mesh.material.uniforms.time.value += 0.01 / 5; // 
      //   }
      // })
    },
    //创建光源 (半球光)
    initLight() {
      let light = new THREE.HemisphereLight(0xffffff, 0x333333, 2);
      light.position.set(0, 0, 100); //点光源位置
      light.position.x = 0;
      light.position.y = 0;
      light.position.z = -200;
      group.add(light);
    },
    // 创建地球
    initEarth() {
      let loader = new THREE.TextureLoader();
      loader.load("./threejs/images/earth.jpg", function (texture) {
        let earth_geometry = new THREE.SphereGeometry(200, 100, 100);
        let earth_material = new THREE.MeshBasicMaterial({
          map: texture,
          overdraw: 0.5,
        });
        earth = new THREE.Mesh(earth_geometry, earth_material);
        earth.name = "地球";
        group.add(earth);
        group.rotation.x = THREE.Math.degToRad(35);
        group.rotation.y = THREE.Math.degToRad(170);
      });
    },
    // 窗口大小改变事件
    onWindowResize() {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    },
    clickLogin() {
      if (this.form.password === "" || this.form.username === "") {
        return this.$message.warning("请输入账号密码！");
      }

      // const regexp = /^[0-9]{4}$/;

      // if (!regexp.test(this.form.captcha)) {
      //   return this.$message.warning("验证码输入错误！");
      // }

      // if (this.form.password === "123456" && this.form.username === "admin") {
      login(this.form).then((response) => {
        const data = response.data;
        if (data.code === 20000) {
          this.$message.warning("登录失败！");
          return;
        } else if (data.msg === "登录失败") {
          this.$message.warning("用户名或密码错误！");
          return;
        }
        const token = data.token;
        //设置token
        cookies.setToken(token); // this.form.username
        cookies.setCookies('current_user',this.form.username);
        // this.$message.success("登录成功！");
        // 发起请求
        this.$router.push("/home");
      });
    },

    run() {
      requestAnimationFrame(this.run);

      let positions = this.sprite.geometry.attributes.position.array;
      let scales = this.sprite.geometry.attributes.scale.array; //BufferGeometry几何体对象具有.attributes属性，BufferGeometry.attributes具有顶点位置、顶点法向量、顶点uv坐标等属性，对应着色器中相应的attribute变量。

      let i = 0,
        j = 0;

      for (let ix = 0; ix < 50; ix++) {
        for (let iy = 0; iy < 50; iy++) {
          positions[i + 1] =
            Math.sin((ix + count) * 0.3) * 50 +
            Math.sin((iy + count) * 0.5) * 50; //y轴上面呈现波浪形

          scales[j] =
            (Math.sin((ix + count) * 0.3) + 1) * 8 +
            (Math.sin((iy + count) * 0.5) + 1) * 8;

          i += 3;
          j++;
        }
      }

      this.sprite.geometry.attributes.position.needsUpdate = true; //通知顶点位置更新
      this.sprite.geometry.attributes.scale.needsUpdate = true;

      renderer.render(scene, camera);
      // status.update();
      count += 0.1;
    },
  },
};
</script>
<style lang="less" scoped>
.login {
  position: relative;
  width: 100%;
  height: 100%;
  // background: url("../../assets/login/login-bg.jpg") no-repeat center center;
  // background-size: 100% 100%;
  background-image: url("../../assets/bg.gif");
  background-repeat: repeat;
  .login-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 450px;
    height: 300px;
    background-color: #00000080;
    // border: solid 2px gray;
    border-radius: 5px;
    padding: 20px 10px;

    // display: flex;
    // flex-direction: column;
    // justify-content: flex-end;
    align-items: center;
    .item {
      width: 100%;
      height: 58px;
      border-bottom: 1px solid #fff;
      input {
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
        border: 0;
        background-color: transparent;
        font-size: 20px;
        outline: none;
        color: #f5f0f0;
      }
      ::v-deep .el-input {
        width: 100%;
        height: 100%;
        color: #f5f0f0;
        input {
          width: 100%;
          height: 100%;
          padding: 0;
          margin: 0;
          border: 0;
          background-color: transparent;
          font-size: 20px;
          outline: none;
          color: #f5f0f0;
          padding-left: 50px;
        }
      }
    }
    .captcha-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      input {
        width: 310px;
        vertical-align: middle;
      }
      .captcha {
        cursor: pointer;
        display: inline-block;
        width: 120px;
        height: 40px;
        background-color: #fff;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }
    .login-btn {
      border-radius: 5px;
      cursor: pointer;
      margin-top: 40px;
      height: 60px;
      width: 100%;
      font-size: 20px;
      color: #fff;
      line-height: 60px;
      text-align: center;
      background: linear-gradient(
        90deg,
        #2192b8 0%,
        rgba(33, 146, 184, 0.5) 50%,
        #2192b8 100%
      );
    }
  }

  .systemEntryBtn {
    position: absolute;
    cursor: pointer;
    right: 150px;
    bottom: 100px;
    width: 120px;
    height: 60px;
    line-height:60px;
    opacity: 0.5;
    color: white;
    // background-color: rgba(0,0,200, 0.5);
    padding-left: 120px;
    background-image: url('../../assets/entry.png');
    background-size: 100% 100%;
  }

  .systemEntryBtn:hover{
    opacity: 1.0;
  }
}
</style>
